package com.cwvs.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.servlet.http.HttpServletRequest;

import nl.bitwalker.useragentutils.Browser;
import nl.bitwalker.useragentutils.OperatingSystem;
import nl.bitwalker.useragentutils.UserAgent;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.NumberUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;

import com.cloopen.rest.sdk.CCPRestSDK;
import com.cwvs.models.ResultInfo;

/**
 * 工具函数
 * 
 * @author mickey
 * 
 */
public class CommonUtils {
	/**
	 * 创建Token
	 * 
	 * @return
	 */
	public static String createToken() {
		return executeMD5(generateString(AppConstants.PASSWORD_SALT_LENGTH)
				+ generateString(AppConstants.PASSWORD_SALT_LENGTH));
	}

	/**
	 * 获取一个指定长度的数字字符串
	 * 
	 * @param length
	 *            返回随机数的长度
	 * @return 字符串
	 */
	public static String generateString(int length) {
		StringBuffer sb = new StringBuffer();

		// 当前时间字符串
		SimpleDateFormat sd = new SimpleDateFormat("yyyyMMddHHmmss");
		sb.append(sd.format(new Date()));

		Random random = new Random();
		for (int i = 0; i < length; i++) {
			// 产生范围是(0~9)的整数，并组合
			sb.append(random.nextInt(10));
		}
		return sb.toString();
	}

	/**
	 * 生产短信验证码
	 * 
	 * @return
	 */
	public static String validateNum(int length) {
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			// 产生范围是(0~9)的整数，并组合
			sb.append(random.nextInt(10));
		}
		return sb.toString();
	}

	/**
	 * 检查邮编格式是否正确
	 * 
	 * @param value
	 * @return
	 */
	public static boolean checkMemberZipCode(String value) {
		return value.matches("[1-9]\\d{5}(?!\\d)");
	}

	/**
	 * 检查固定电话格式是否正确
	 * 
	 * @param value
	 * @return
	 */
	public static boolean checkMemberFixedPhone(String value) {
		return value.matches("\\d{3}-\\d{7,8}|\\d{4}-\\d{7,8}");
	}

	/**
     * 
     */
	public static boolean checkRealName(String value) {
		return value.matches("^[\u4e00-\u9fa5a-zA-Z]*");
	}

	/**
	 * 检查手机格式是否正确
	 * 
	 * @param value
	 * @return
	 */
	public static boolean checkMemberMobilePhone(String value) {
		return value.matches("^[1]+\\d{10}");
	}

	public static boolean checkQQ(String value) {
		return value.matches("^[1-9]+\\d{4,10}");
	}

	/**
	 * 匹配用户名字符组成
	 * 
	 * @param value
	 * @return
	 */
	public static boolean checkUserName(String value) {
		return value.matches("^[\u4E00-\u9FA5a-zA-Z0-9_]*");
	}

	/**
	 * 邮箱格式匹配
	 * 
	 * @param value
	 * @return
	 */
	public static boolean checkMemberEmail(String value) {
		Pattern pattern = Pattern.compile(
				"[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+",
				Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(value);
		if (matcher.matches()) {
			// StringBuffer bf=new StringBuffer(value);
			// if(bf.indexOf("@")<5){
			// return false;
			// }
			// if(bf.indexOf("@")>18)
			// {
			// return false;
			// }
			return true;
		}
		return false;
	}

	/**
	 * 验证密码
	 * 
	 * @param newPassword
	 * @param retPassword
	 * @return
	 */
	public static String checkPassword(String newPassword, String retPassword) {
		if (StringUtils.isBlank(newPassword)
				|| StringUtils.isBlank(retPassword)) {
			return "请输入密码!";
		}
		if (newPassword.length() < 6 || newPassword.length() > 16
				|| retPassword.length() < 6 || retPassword.length() > 16) {
			return "密码长度只能在6-16位字符之间!";
		}
		// if (CommonUtil.isNumeric(newPassword)
		// || CommonUtil.isNumeric(retPassword)) {
		// return "新密码不能全为数字!";
		// }
		// if (CommonUtil.isLetters(retPassword)
		// || CommonUtil.isLetters(newPassword)) {
		// return "新密码不能全为字母!";
		// }
		if (!newPassword.equals(retPassword)) {
			return "密码输入不一致!";
		}
		return null;
	}

	/**
	 * 盐值加密
	 * 
	 * @param currentPwd
	 * @param salt
	 * @return 字符串
	 */
	public static String passwordToPasswordSalt(String currentPassword,
			String passwordSalt) {
		return executeMD5(currentPassword + passwordSalt);
	}

	/**
	 * 验证输入密码与原密码是否匹配
	 * 
	 * @param userPwd
	 * @param userPwdSalt
	 * @param currentPwd
	 * @return
	 */
	public static boolean userPwdIsExist(String userPassword,
			String passwordSalt, String currentPassword) {
		String subPassword = currentPassword + passwordSalt;

		if (executeMD5(subPassword).equals(userPassword)) {
			return true;
		}
		return false;
	}

	/**
	 * MD5加密(32位)
	 * 
	 * @param inStr
	 *            源密码
	 * @return 加密后密码
	 */
	public static String executeMD5(String inStr) {
		MessageDigest md5 = null;
		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			return "";
		}
		char[] charArray = inStr.toCharArray();
		byte[] byteArray = new byte[charArray.length];

		for (int i = 0; i < charArray.length; i++)
			byteArray[i] = (byte) charArray[i];

		byte[] md5Bytes = md5.digest(byteArray);

		StringBuffer hexValue = new StringBuffer();

		for (int i = 0; i < md5Bytes.length; i++) {
			int val = ((int) md5Bytes[i]) & 0xff;
			if (val < 16)
				hexValue.append("0");
			hexValue.append(Integer.toHexString(val));
		}

		return hexValue.toString();
	}

	/**
	 * 产生对应的加密des + base64 加密串
	 * 
	 * @param message
	 * @param key
	 *            密钥
	 * @return
	 * @throws Exception
	 */
	public static String encrypt(String message, String key) {
		if (StringUtils.isBlank(message) || StringUtils.isBlank(key)) {
			return null;
		}
		try {
			Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
			DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
			IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
			cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
			byte[] encryptbyte = cipher.doFinal(message.getBytes());
			Base64 base64Encoder = new Base64();
			if (StringUtils.isNotBlank(message)) {
				return base64Encoder.encodeToString(encryptbyte);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@SuppressWarnings("rawtypes")
	public static Map<Object, Object> encryptMap(Map map, String key) {
		HashMap<Object, Object> hashMap = new HashMap<Object, Object>();
		Object[] mapKey = map.keySet().toArray();
		Arrays.sort(mapKey);
		for (int i = 0; i < mapKey.length; i++) {
			if (map.get(mapKey[i]) == null) {
				hashMap.put(mapKey[i], encrypt("", key));
			} else {
				hashMap.put(mapKey[i],
						encrypt(String.valueOf(map.get(mapKey[i])), key));
			}
		}
		return hashMap;
	}

	/**
	 * base64 + des 解密加密后的字符串
	 * 
	 * @param message
	 * @param key
	 *            密钥
	 * @return
	 * @throws Exception
	 */
	public static String decrypt(String message, String key) throws Exception {
		if (StringUtils.isBlank(message) || StringUtils.isBlank(key)) {
			return null;
		}
		Base64 base64Decoder = new Base64();
		byte[] bytesrc = base64Decoder.decode(message);
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
		IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
		cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
		byte[] retByte = cipher.doFinal(bytesrc);
		return new String(retByte);
	}

	/**
	 * base64 + des 解密map
	 * 
	 * @param message
	 * @param key
	 *            密钥
	 * @return
	 * @throws Exception
	 */
	public static Map<String, String> decrypt(Map<String, String> map,
			String key) throws Exception {
		HashMap<String, String> hashMap = new HashMap<String, String>();
		Object[] mapKey = map.keySet().toArray();
		Arrays.sort(mapKey);
		for (int i = 0; i < mapKey.length; i++) {
			hashMap.put(mapKey[i].toString(), decrypt(map.get(mapKey[i]), key));
		}
		return hashMap;
	}

	/**
	 * 判断字符串是否为全数字
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);
		if (!isNum.matches()) {
			return false;
		}
		return true;
	}

	/**
	 * 判断字符串是否为全字母
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isLetters(String str) {
		for (int i = 0; i < str.length(); i++) {
			if (!(str.charAt(i) >= 'A' && str.charAt(i) <= 'Z')
					&& !(str.charAt(i) >= 'a' && str.charAt(i) <= 'z')) {
				return false;
			}
		}
		return true;
	}

	public static ResponseEntity<String> getResponseEntity(Object object) {
		HttpHeaders headers = new HttpHeaders();
		MediaType mt = new MediaType("text", "html", Charset.forName("UTF-8"));
		headers.setContentType(mt);
		String body = JsonUtil.toJson(object);
		ResponseEntity<String> re = new ResponseEntity<String>(body, headers,
				HttpStatus.OK);
		return re;
	}

	public static Properties config(String propertiesName) {
		DefaultResourceLoader loader = new DefaultResourceLoader();
		Properties props = new Properties();
		try {
			props.load(loader.getResource(propertiesName).getInputStream());
		} catch (IOException e) {
			throw new RuntimeException("读配置文件错误,错误信息:" + e.getMessage());
		}
		return props;
	}

	public static ResponseEntity<String> getResponseEntityFromJson(
			String jsonData) {
		HttpHeaders headers = new HttpHeaders();
		MediaType mt = new MediaType("text", "html", Charset.forName("UTF-8"));
		headers.setContentType(mt);
		String body = jsonData;
		ResponseEntity<String> re = new ResponseEntity<String>(body, headers,
				HttpStatus.OK);
		return re;
	}

	/**
	 * 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割 <br/>
	 * "***.***.***.***".length()
	 * 
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ipAddress = getRawIpAddr(request);

		if (StringUtils.isBlank(ipAddress)) {
			return "";
		}

		if (ipAddress.length() <= 15) {
			return ipAddress;
		}

		if (ipAddress.indexOf(",") == -1) {
			return ipAddress;
		}

		return StringUtils.substringBefore(ipAddress, ",");
	}

	/**
	 * 获取原始的ip地址,可能会有多个ip,多个IP按照','分割
	 * 
	 * @param request
	 * @return
	 */
	public static String getRawIpAddr(HttpServletRequest request) {
		{
			String ret = request.getHeader("X-Forwarded-For2");
			if (StringUtils.isNotBlank(ret) && "unknown".equalsIgnoreCase(ret)) {
				return ret;
			}
		}
		{
			String ret = request.getHeader("X-Forwarded-For");
			if (StringUtils.isNotBlank(ret) && "unknown".equalsIgnoreCase(ret)) {
				return ret;
			}
		}
		{
			String ret = request.getHeader("Client-IP");
			if (StringUtils.isNotBlank(ret) && "unknown".equalsIgnoreCase(ret)) {
				return ret;
			}
		}
		{
			String ret = request.getHeader("Proxy-Client-IP");
			if (StringUtils.isNotBlank(ret) && "unknown".equalsIgnoreCase(ret)) {
				return ret;
			}
		}
		{
			String ret = request.getHeader("WL-Proxy-Client-IP");
			if (StringUtils.isNotBlank(ret) && "unknown".equalsIgnoreCase(ret)) {
				return ret;
			}
		}
		{
			String ret = request.getRemoteAddr();
			if (StringUtils.isNotBlank(ret)) {
				return ret;
			}
		}

		return "";
	}

	public static String getIpAddress(HttpServletRequest request) {
		String ipAddress = null;
		// ipAddress = this.getRequest().getRemoteAddr();
		ipAddress = request.getHeader("x-forwarded-for");
		if (ipAddress == null || ipAddress.length() == 0
				|| "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0
				|| "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0
				|| "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getRemoteAddr();
			if (ipAddress.equals("127.0.0.1")) {
				// 根据网卡取本机配置的IP
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
				ipAddress = inet.getHostAddress();
			}

		}

		// 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
		if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
															// = 15
			if (ipAddress.indexOf(",") > 0) {
				ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
			}
		}
		return ipAddress;
	}

	@SuppressWarnings("deprecation")
	public static boolean isInteger(String str) {
		if (StringUtils.isEmpty(str)) {
			return false;
		}
		if (str.indexOf(".") != -1 || str.indexOf("x") != -1
				|| str.indexOf("E") != -1 || str.indexOf("e") != -1) {
			return false;
		}

		return NumberUtils.isNumber(str);
	}

	public static String DateToStr(Date date) {
		String str = "";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if (date != null) {
			str = sdf.format(date);
		}
		return str;
	}

	public static String DateToStr(Date date, String format) {
		String str = "";
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		if (date != null) {
			str = sdf.format(date);
		}
		return str;
	}

	public static Date stringToDate(String str) {
		Date date;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if (str != null && !"".equals(str)) {
			try {
				date = sdf.parse(str);
			} catch (ParseException e) {
				date = null;
				e.printStackTrace();
			}
		} else {
			date = null;
		}
		return date;
	}

	public static Date stringToDateTime(String str) {
		Date date;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if (str != null && !"".equals(str)) {
			try {
				date = sdf.parse(str);
			} catch (ParseException e) {
				date = null;
				e.printStackTrace();
			}
		} else {
			date = null;
		}
		return date;
	}

	public static Date stringToDate(String str, String format) {
		Date date;
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		if (str != null && !"".equals(str)) {
			try {
				date = sdf.parse(str);
			} catch (ParseException e) {
				date = null;
				e.printStackTrace();
			}
		} else {
			date = null;
		}
		return date;
	}

	/**
	 * 检查邮编格式是否正确
	 * 
	 * @param value
	 * @return
	 */
	public static boolean checkZipCode(String value) {
		return value.matches("[1-9]\\d{5}(?!\\d)");
	}

	/**
	 * 检查固定电话格式是否正确
	 * 
	 * @param value
	 * @return
	 */
	public static boolean checkFixedPhone(String value) {
		return value.matches("\\d{3}-\\d{7,8}|\\d{4}-\\d{7,8}");
	}

	/**
	 * 检查手机格式是否正确
	 * 
	 * @param value
	 * @return
	 */
	public static boolean checkMobilePhone(String value) {
		return value.matches("^[1][3,5,8]+\\d{9}");
	}

	/**
	 * 匹配用户名字符组成
	 * 
	 * @param value
	 * @return
	 */
	public static boolean checkUserTrueName(String value) {
		return value.matches("^[\u4E00-\u9FA5]*");
	}

	/**
	 * 邮箱格式匹配
	 * 
	 * @param value
	 * @return
	 */
	public static boolean checkEmail(String value) {
		Pattern pattern = Pattern.compile(
				"[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+",
				Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(value);
		if (matcher.matches()) {
			StringBuffer bf = new StringBuffer(value);
			if (bf.indexOf("@") < 5) {
				return false;
			}
			return true;
		}
		return false;
	}

	/**
	 * 判断失效时间是否属于置顶
	 * 
	 * @param str
	 * @return
	 */
	public static boolean checkZhiDingDate(Date date) {
		Date now = new Date();
		if (now.after(date)) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * 生成指定长度的流水号
	 * 
	 * @param length
	 *            生成流水号的位数
	 * @param num
	 *            原始数字
	 * @return
	 */
	public static String generateString(int length, Object num) {
		String str = "";
		if (num == null) {
			return null;
		} else {
			int tempLen = length - num.toString().length();
			if (tempLen < 0) {
				return str + num;
			}
			for (int i = 0; i < tempLen; i++) {
				str += "0";
			}
			return str + num;
		}
	}

	public static Map<String, Object> checkReturnMap(
			Map<String, String[]> option, Iterator<String> paramsName) {
		Map<String, Object> con = new HashMap<String, Object>();
		String tempKey = "";
		if (paramsName != null && option != null) {
			while (paramsName.hasNext()) {
				tempKey = paramsName.next();
				if (option.containsKey(tempKey)) {
					con.put(tempKey, option.get(tempKey)[0]);
				}
			}
		}
		return con;
	}

	public static Object checkObjectNull(Object obj) {
		if (obj == null) {
			return "";
		}
		return obj;
	}

	/**
	 * 获取几天后的时间
	 * 
	 * @return
	 */
	public static Date getDate(Date dt, Double day) {
		return new Date((long) (dt.getTime() + day * 24 * 60 * 60 * 1000));
	}

	public static String getFile(String fileRoot,MultipartFile imgFile, String type,
			List<String> fileTypes) {
		fileRoot = handleFilePath(fileRoot);
		if (StringUtils.isBlank(fileRoot)) {
			return null;
		}
		String floderName = handleFilePath(handleFilePath(fileRoot) + type)
				+ new SimpleDateFormat("yyyyMMdd").format(new Date());
		String uuid = UUID.randomUUID().toString();
		String fileName = uuid
				+ imgFile.getOriginalFilename().substring(
						imgFile.getOriginalFilename().lastIndexOf("."));
		String ext = fileName.substring(fileName.lastIndexOf(".") + 1,
				fileName.length());
		// 对扩展名进行小写转换
		ext = ext.toLowerCase();
		File file = null;
		if (fileTypes.contains(ext)) { // 如果扩展名属于允许上传的类型，则创建文件
			File dir = new File(floderName);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			file = new File(handleFilePath(floderName) + fileName);
			if (file.exists()) {
				file.delete();
			}
			try {
				file.createNewFile();
				imgFile.transferTo(file); // 保存上传的文件
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return (handleFilePath(floderName) + fileName).substring(fileRoot.length());
		}
		return null;
	}

	/**
	 * 处理文件位置
	 * 
	 * @param fileName
	 * @return
	 */
	private static String handleFilePath(String fileName) {
		if (null != fileName) {
			fileName = fileName.replace("\\", "/");
			if (!fileName.endsWith("/")) {
				fileName += "/";
			}
		}
		return fileName;
	}

	public static String getValue(String fileNamePath, String key)
			throws IOException {
		Properties props = new Properties();
		InputStream in = null;
		try {
			in = Object.class.getResourceAsStream(fileNamePath);
			// 如果将in改为下面的方法，必须要将.Properties文件和此class类文件放在同一个包中
			// in = propertiesTools.class.getResourceAsStream(fileNamePath);
			props.load(in);
			String value = props.getProperty(key);
			// 有乱码时要进行重新编码
			new String(props.getProperty(key).getBytes("ISO-8859-1"), "GBK");
			return value;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} finally {
			if (null != in)
				in.close();
		}
	}

	/**
	 * 通过类型获取类型名称
	 * 
	 * @param type
	 * @return
	 */
	public static String getStoreTypeName(String type) {
		if (StringUtils.equals("0", type)) {
			return "订座店铺";
		}
		if (StringUtils.equals("1", type)) {
			return "外卖店铺";
		}
		if (StringUtils.equals("2", type)) {
			return "挂号医院";
		}
		return null;
	}
	
	/**
	 * 短信发送
	 */
	public static ResultInfo sendSms(String to,String tempId,String[] content){
		ResultInfo res=new ResultInfo();
		CCPRestSDK restAPI = new CCPRestSDK();
		restAPI.init("app.cloopen.com", "8883");// 初始化服务器地址和端口，格式如下，服务器地址不需要写https://
//		restAPI.setAccount("accountSid", "accountToken");// 初始化主帐号名称和主帐号令牌
		restAPI.setAccount(AppConstants.SMS_ACCOUNT_SID, AppConstants.SMS_ACCOUNT_TOKEN);// 初始化主帐号名称和主帐号令牌
		restAPI.setAppId(AppConstants.SMS_APP_ID);// 初始化应用ID
		HashMap<String, Object>  result = restAPI.sendTemplateSMS(to,tempId ,content);
		if("000000".equals(result.get("statusCode"))){
			res.setSuccess(true);
			res.setMessage("短信发送成功");
			return res;
			//正常返回输出data包体信息（map）
//			HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
//			Set<String> keySet = data.keySet();
//			for(String key:keySet){
//				Object object = data.get(key);
//				System.out.println(key +" = "+object);
//			}
		}else{
			res.setSuccess(false);
			res.setMessage((String)result.get("statusMsg"));
			return res;
			//异常返回输出错误码和错误信息
//			System.out.println("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
		}
	}
	public static Map<String,Object> getAgent(String agent){
	    Map<String,Object> map=	new HashMap<String,Object>();
		UserAgent userAgent = UserAgent.parseUserAgentString(agent);  
	    Browser browser = userAgent.getBrowser();  
	    OperatingSystem os = userAgent.getOperatingSystem();
		Pattern pattern = Pattern.compile(";\\s?(\\S*?\\s?\\S*?)\\s?(Build)?/");  
	    Matcher matcher = pattern.matcher(agent);
	    map.put("browser", browser.getName());
	    map.put("os", os.getName());
	    String model = null;  
	    if (matcher.find()) {  
	        model = matcher.group(1).trim();  
	        map.put("mobile", model);
	    }
	    return map;
	}
}
